<template>
  <el-button v-if="hasPermission(permission)" v-action="permission" v-bind="$attrs" :loading="loading" @click="handleClick">
    <Icon v-if="icon" :name="icon" :className="iconClass" />
    <slot></slot>
  </el-button>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/modules/user'

interface Props {
  permission: string // 权限标识，如 'enroll@MemEnroll@storeContactLog'
  icon?: string // 图标名称，可选
  iconClass?: string // 图标样式类，默认 'w-4 h-4 mr-1'
  loading?: boolean // 是否加载中，默认 false
}

const props = withDefaults(defineProps<Props>(), {
  iconClass: 'w-4 h-4 mr-1',
  loading: false
})

const emit = defineEmits<{
  click: [event: MouseEvent]
}>()

// 获取用户权限信息
const userStore = useUserStore()
const userHasPermissions = userStore.getPermissions
const userActions = userStore.getActions

// 权限检查函数
const hasPermission = (mark: string): boolean => {
  if (!userHasPermissions || userHasPermissions.length === 0) {
    console.warn(`权限检查失败 - 用户权限为空: ${mark}`)
    return false
  }

  // 方法1：检查原始权限数据 (推荐)
  for (const item of userHasPermissions) {
    const permissionKey = item.module + '@' + item.permission_mark
    if (permissionKey === mark) {
      return true
    }
  }

  // 方法2：检查actions数组格式 (备用兼容)
  if (userActions && userActions.length > 0) {
    const actionFormat = mark.replace(/@/g, '.').toLowerCase()
    if (userActions.includes(actionFormat)) {
      return true
    }
  }

  return false
}

// 点击事件处理
const handleClick = (event: MouseEvent) => {
  if (hasPermission(props.permission)) {
    emit('click', event)
  } else {
    console.warn(`权限不足，无法执行操作: ${props.permission}`)
  }
}
</script>
